//
//  OAuthViewController.swift
//  PersonnalDiary
//
//  Created by 徐宽阔 on 15/9/29.
//  Copyright © 2015年 XDKOO. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAuthViewController: UIViewController {
    
    let WB_App_Key: String = "502207787"
    let WB_App_Secret: String = "8b75ec8222449174238dce3684d88a73"
    let WB_Redirect_URI = "http://baidu.com"
    
    override func loadView() {
        webView.delegate = self
        view = webView
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.whiteColor()
        
        navigationItem.title = "新浪微博"
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Done, target: self, action: Selector("close"))
        
        let urlStr = "https://api.weibo.com/oauth2/authorize?client_id=" + WB_App_Key + "&redirect_uri=" + WB_Redirect_URI
        let url = NSURL(string: urlStr)!
        let request = NSURLRequest(URL: url)
        webView.loadRequest(request)
        
    }
    
    func close()
    {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
//    private lazy var webView: UIWebView = {
//        let webView = UIWebView()
//        webView.frame = UIScreen.mainScreen().bounds
//        return  webView
//    }()
    
    private lazy var webView = UIWebView()

}

extension OAuthViewController: UIWebViewDelegate
{
    // MARK: UIWebViewDelegate
    
    func webViewDidStartLoad(webView: UIWebView)
    {
        SVProgressHUD.showSuccessWithStatus("正在加载登录界面ing...", maskType: SVProgressHUDMaskType.Black)
    }
    
    func webViewDidFinishLoad(webView: UIWebView)
    {
        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool
    {
        let URLStr = request.URL!.absoluteString
        if !URLStr.hasPrefix(WB_Redirect_URI)
        {
            return true
        }
        let codeStr = "code="
        if !URLStr.containsString("error")
        {
            XDKLog("授权成功")
            // URL中的query是专门用于查询URL中的参数的
            // 会将?后面的字符串返回给我们
            let code = request.URL!.query!.substringFromIndex(codeStr.endIndex)
            XDKLog(code)
            
            loadAccessToken(code)
        }else{
            XDKLog("授权失败")
            close()
        }
        return false
    }
    
    // MARK: - 获取access_token
    
    private func loadAccessToken(code: String)
    {
        let path = "oauth2/access_token"
        
        let params = ["client_id": WB_App_Key,
                        "client_secret": WB_App_Secret,
                        "grant_type": "authorization_code",
                        "code": code,
                        "redirect_uri": WB_Redirect_URI]
        
        NetworkTools.shareNetworkTools().POST(path, parameters: params, success: { (_, dict) -> Void in
//            let data = try! NSJSONSerialization.dataWithJSONObject(dict, options: NSJSONWritingOptions.PrettyPrinted)
//            let str = String(data: data, encoding: NSUTF8StringEncoding)
//            XDKLog(str)
            
            let account = UserAccount(dict: dict as! [String : AnyObject])
            
            account.loadUserInfo { (account, error) -> () in
                if account != nil
                {
                    account?.saveAccount()
                    return
                }
                
                SVProgressHUD.showErrorWithStatus("获取授权信息失败", maskType: SVProgressHUDMaskType.Black)
            }
            
            
            }) { (_, error) -> Void in
                SVProgressHUD.showErrorWithStatus("获取授权信息失败", maskType: SVProgressHUDMaskType.Black)
        }
    }
}
